# -*- coding: utf-8 -*-
class AdminController < ApplicationController
  before_filter :sys_before_log
  before_filter :privilege_filter,:except=>[:getRolePrivilegeById,:getRolePrivilegeDetailsById,:clearTestDataView,:reindexView,:calCostPriceView,:roleWarehouse,:getRoleWarehouse,:roleWarehouseLock]

  #显示清空数据的网页介面。
  def clearTestDataView

  end

  #角色设置
  def rolePrivilege

  end

  #显示添加角色页面
  def newRole

  end

  #显示编辑角色页面
  def editRole

  end

  #系统日志。
  def logList

  end

  #登录日志
  def loginLogList

  end

  #数据维护
  def dataManager

  end

  #用户自行修改密码的介面
  def changePasswordView

  end

  #得到所有的根模块
  def getAllModules
    modules = Privilege.find(:all,:conditions=>['parent_id = 0'],:order=>'sort_id')
    jsonStr="{totalProperty:"+modules.length.to_s+",root:"+modules.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #
  def getAllSysControllers
    sysControllers = SysController.find(:all,:order=>'name')
    jsonStr="{totalProperty:"+sysControllers.length.to_s+",root:"+sysControllers.to_json()+"}"
    render :text=>jsonStr, :layout=>false
  end

  #
  def getAllSysActions
    if params[:sys_controller_id] == nil
      sysActions = SysAction.find(:all,:order=>'name')
    else
      sysActions = SysAction.find(:all,:conditions=>["sys_controller_id = ?",params[:sys_controller_id]],:order=>'name')
    end
    jsonStr="{totalProperty:"+sysActions.length.to_s+",root:"+sysActions.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #
  def getAllSysLog
    start = params[:start]
    limit = params[:limit]
    dblogs = DbLog.paginate start,limit

    jsonStr="{totalProperty:"+DbLog.count.to_s+",root:"+dblogs.to_json(:include=>[:company,:department,:employee])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #获得系统登录日志
  def getAllSysLoginLog
    name =  params[:name]
    if name == nil || name == ''
      count = LoginLog.count
      loginLogs = LoginLog.find(
        :all,
        :offset => params[:start].to_i,
        :include=>[:company,:department,:employee],
        :limit => params[:limit].to_i,
        :order=> "id DESC"
      )
    else
      name = '%'+name+'%'
      count = LoginLog.find(
        :all,
        :select => 'id',
        :conditions=> ['name like ?',name],
        :order=> "id DESC"
      ).count

      loginLogs = LoginLog.find(
        :all,
        :offset => params[:start].to_i,
        :conditions=> ['name like ?',name],
        :include=>[:company,:department,:employee],
        :limit => params[:limit].to_i,
        :order=> "id DESC"
      )
    end
    jsonStr="{totalProperty:"+count.to_s+",root:"+loginLogs.to_json(:include=>[:company,:department,:employee])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到所有的用户行为日志
  def getAllActionHxes
    start = params[:start]
    limit = params[:limit]
    employeeId = params[:employee_id]
    employeeActionHxes = EmployeeActionHx.paginate employeeId,start.to_i,limit.to_i
    pageCount = EmployeeActionHx.page_count employeeId
    jsonStr="{totalProperty:"+pageCount.count.to_s+",root:"+employeeActionHxes.to_json(:include=>[:company,:department,:employee,:role])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据ID得到角色权限树
  def getRolePrivilegeById
    nodeId =  params["node"]
    #作一些处理，因为传来的nodeId可能出现怪值。
    if nodeId == nil || (nodeId.include? "xnode-") || nodeId == "0"
      is_root = true
      nodeId = 0
    end
    privileges  = Privilege.find(:all,:conditions=>["parent_id = ? AND is_locked = 0",nodeId],:order=>'sort_id')
    treeData="["
    privileges.each do |privilege|
      #treeData.concat("{id:#{privilege.id},text:\"#{privilege.name}\",leaf:#{privilege.leaf}},")
      treeData.concat("{id:#{privilege.id},text:\"#{privilege.name}\"")
      if privilege.level == 0
        treeData.concat(",leaf:false")
      else
        treeData.concat(",leaf:true")
      end
      if privilege.is_locked == 1
        treeData.concat(",checked:true},")
      else
        treeData.concat(",checked:false},")
      end
    end
    treeData = treeData[0,treeData.size-1]
    treeData.concat("]")
    logger.info treeData
    jsonStr = treeData
    render :text=>jsonStr, :layout=>false
  end


  #得到某一权限下，某角色的详细项。
  def getRolePrivilegeDetailsById
    #此处要得到3个参加1.公司，2.角色，3.权限
    logger.info "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    logger.info params[:role_id]
    role = Role.find(params[:role_id])
    #在这里，角色中的privilege已经深化为menu_id，是一系列相关权限细节的集合
    rolePrivilegeDetails = RolesPrivilegeDetail.find(:all,:conditions=>["menu_id = ? AND role_id = ?",params[:privilege_id],params[:role_id]])
    #同时也要得到系统中的权限细节，然后用系统中的权限细节和个人的权限细节进行对比，有则不动，无则加，如果角色有，系统没有，则删。、
    Privilege.transaction do
      sysPrivilegeDetails = Privilege.getUnlockedSysPrivilegeDetailsForRole(params[:privilege_id])

      if sysPrivilegeDetails != nil
        #如果此时角色还没有分配过权限细节，则把现有系统权限一次性追加上。
        if rolePrivilegeDetails.length == 0
          sysPrivilegeDetails.each do |sysPrivilegeDetail|
            rolesPrivilegeDetail = RolesPrivilegeDetail.new
            rolesPrivilegeDetail.module_id = params[:parent_privilege_id]
            rolesPrivilegeDetail.menu_id = params[:privilege_id]
            rolesPrivilegeDetail.privilege_detail_id  = sysPrivilegeDetail.id
            role.roles_privilege_details << rolesPrivilegeDetail
          end
        else
          #分二次循环，一是查是否有多的，第二次是查是滞有少的。
          #有不动，少则加，多则删
          #privilegeAction有三个值，1.add,2.remove,3.nil,""就是无动作
          privilegeAction = nil
          rolePrivilegeDetails.each do |rolePrivilegeDetail|
            privilegeAction = "remove"
            sysPrivilegeDetails.each do |sysPrivilegeDetail|
              if rolePrivilegeDetail.privilege_detail_id ==  sysPrivilegeDetail.id
                privilegeAction = nil
              end
            end
            if privilegeAction == "remove"
              rolePrivilegeDetails.delete(rolePrivilegeDetail)
            end
          end
          #第二次循环，就是添加
          privilegeAction = nil
          sysPrivilegeDetails.each do |sysPrivilegeDetail|
            privilegeAction = "add"
            rolePrivilegeDetails.each do |rolePrivilegeDetail|
              if rolePrivilegeDetail.privilege_detail_id ==  sysPrivilegeDetail.id
                privilegeAction = nil
              end
            end
            if privilegeAction == "add"
              rolesPrivilegeDetail = RolesPrivilegeDetail.new
              rolesPrivilegeDetail.module_id = params[:parent_privilege_id]
              rolesPrivilegeDetail.menu_id = params[:privilege_id]
              rolesPrivilegeDetail.privilege_detail_id  = sysPrivilegeDetail.id
              role.roles_privilege_details << rolesPrivilegeDetail
            end
          end
        end
      end
    end

    rolePrivilegeDetails = RolesPrivilegeDetail.find(:all,:include => [:privilege_detail],:conditions=>["menu_id = ? AND role_id = ?",params[:privilege_id],params[:role_id]])
    jsonStr="{totalProperty:"+rolePrivilegeDetails.length.to_s+",root:"+rolePrivilegeDetails.to_json(:include=>[:privilege_detail])+"}"
    render :text=>jsonStr, :layout=>false
  end



  #角色的解锁与锁定
  def roleLock
    role = Role.find(params[:id])
    if role.is_locked == 1
      role.is_locked = 0
    else
      role.is_locked = 1
    end
    role.save
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end


  #得到某一公司下的所有角色
  def getAllRoles
    forCBB = params[:for_cbb]
    if forCBB == 'true'
      roles = Role.find(:all,:conditions=>["is_locked = 0"])
    else
      roles = Role.find(:all)
    end

    jsonStr="{totalProperty:"+roles.length.to_s+",root:"+roles.to_json()+"}"
    render :text=>jsonStr, :layout=>false
  end

  def createRole
    role = Role.new
    role.name = params[:name]
    role.description = params[:description]
    role.save
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getRoleById
    role = Role.find(params[:id])
    rootStr = role.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #把编辑后的数据，更新到数据库中
  def updateRole

    begin
      role = Role.find(params[:id])
      role.name = params[:name]
      role.description = params[:description]
      role.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info( params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到个人的权限
  def getPersonPrivileges

    roleId = session[:role_id]
    
    rolesPrivilegeDetails = RolesPrivilegeDetail.find_by_sql("select distinct pd.privilege_id as privilege_id,p.name as name from roles_privilege_details pd,privileges p where p.level = 0 AND pd.privilege_id = p.id AND pd.role_id = #{roleId}")
    jsonStr="{totalProperty:"+rolesPrivilegeDetails.length.to_s+",root:"+rolesPrivilegeDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #用户自行修改密码
  def changePassword
    employee =  Employee.find(session[:employee_id])
    employee.password = params[:password]
    employee.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #系统参数的设置，保存审批相关的参数状态。
  def updateAuditParams

  end
end
